let commonUserInfo = {}, t = new Date().getTime();
class Login {
    /**
    * 天地图用户登录接口
    * @param login    登录地址
    * @param logout   登出地址
    * @param userInfo 获取用户信息接口
    * @param callback 用户信息获取完成之后回调函数
    * @param projectName 项目名称：data|layers|visual
    */
    constructor({ login,ssoLogin, logout, userInfo, callback, projectName }) {
        this.start({ login,ssoLogin, logout, userInfo, callback, projectName });
    }
    /**
     * 启动
     */
    start(User) {
      this.User = User;
      this.jsonpRequest(User);
    }
    /**
     * 点击登录按钮
     * @param loginUrl
     * @param loginRedirectUrl 登录成功之后需要跳转的url
     */
    signIn(loginRedirectUrl) {
        const loginUrl = this.User.login;
        let url = loginRedirectUrl ? loginRedirectUrl : window.location.href;
        url = loginUrl + "?url=" + encodeURIComponent(encodeURIComponent(url));
        window.location.href = url;
    }
    /**
     * 点击登出按钮
     * @param logoutUrl
     * @param logoutRedirectUrl 退出成功之后需要跳转的url
     */
    signOut(logoutRedirectUrl) {
        const logoutUrl = this.User.logout;
        let url = logoutRedirectUrl ? logoutRedirectUrl : window.location.href;
        url = logoutUrl + "?url=" + encodeURIComponent(encodeURIComponent(url));
        window.location.href = url;
    }
    init() {
        // 登录初始化
        if (!this.User || !this.User.login) {
            return;
        }
        this.signIn(this.User.ssoLogin);
    }
    /**
    * 跨域请求
    */
    jsonpRequest() {
        let { userInfo, callback } = this.User;
        const callbackBind = callback.bind(this);

        let script = document.createElement('script');
        script.id = 'userInfo';
        script.src = userInfo + '?callback=getUserInfo' + t;
        let body = document.getElementsByTagName("BODY")[0];
        body.appendChild(script);

        script.onload = function () {
            body.removeChild(script);
            if (typeof callbackBind === 'function') {

                callbackBind(commonUserInfo);
            }
        }

        script.onerror = function () {
            body.removeChild(script);
            if (typeof callbackBind === 'function') {

                commonUserInfo.error = true;
                callbackBind(commonUserInfo);
            }
        }
    }
    /**
     * 个人信息中心
     */
    personalInfo(UMS_URL) {
        window.open(UMS_URL, '_blank');
    }
}

/**
 * 用户登录成功之后的回调函数
 * @param res 用户详细信息
 */
window['getUserInfo' + t] = function (res) {
    commonUserInfo = res;
};

export default Login;
